package com.edu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.demo.entity.*;
import com.edu.demo.mapper.*;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.service.IProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.demo.service.ITaskService;
import com.edu.demo.utils.SecurityUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jixuewei
 * @since 2023-01-12
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {


    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private MediumTermMapper mediumTermMapper;

    @Autowired
    private DepartmentMapper departmentMapper;


    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private ProResumeMapper resumeMapper;

    @Autowired
    private StudentMapper studentMapper;




    @Autowired
    private RedisTemplate<String,Object>  redisTemplate;

    /**
     * 项目列表，分页查询
     *
     * @param index
     * @param size
     * @param
     * @return
     */
    @Override
    public List<Project> projectList(int index, int size,AjaxResult result) {
        IPage<Project> page = new Page<>(index,size);
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.eq("conclusion",0);
        wrapper.eq("revoked",0);
        IPage<Project> page1 = projectMapper.selectPage(page, wrapper);
        result.put("total",page1.getTotal());
        return page1.getRecords();
    }

    /**
     * 新添加一个项目
     *
     * @param project
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProject(Project project) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Teacher teacher = loginUser.getTeacher();
        project.settName(teacher.getName());
        project.settId(teacher.getId());
        int insert = projectMapper.insert(project);
        List<Task> tasks = project.getTasks();
        for (Task task : tasks) {
            task.setProjectId(project.getId());
        }
        taskService.saveBatch(tasks);
        return 0;
    }

    /**
     * 查找指定条件的项目
     *
     * @param project
     * @return
     */
    @Override
    public List<Project> queryProject(Project project,int index,int size,AjaxResult ajaxResult) {
        IPage<Project> page = new Page<>(index,size);
        QueryWrapper<Project> wrapper = new QueryWrapper<>();

        if(Strings.isNotEmpty(project.getTitle()))
            wrapper.likeLeft("title",project.getTitle());
        if(Strings.isNotEmpty(project.gettName()))
            wrapper.likeLeft("t_name",project.gettName());
        if(!Objects.isNull(project.getStatus())){
            wrapper.eq("status",project.getStatus());
        }
        if(!Objects.isNull(project.gettId())){
            wrapper.eq("t_id",project.gettId());
        }
        if(!Objects.isNull(project.getMidTerm()))
            wrapper.eq("mid_term",project.getMidTerm());
        if(!Objects.isNull(project.getConclusion())) {
            wrapper.eq("conclusion", project.getConclusion());
        }
        if(!Objects.isNull(project.getReleaseTime())) {


            Date releaseTime = project.getReleaseTime();
            releaseTime.setHours(0);
            Date date = (Date) releaseTime.clone();
            date.setHours(23);
            date.setMinutes(59);
            wrapper.ge("release_time", releaseTime);
            wrapper.le("release_time", date);
        }
        if(!Objects.isNull(project.getDeadline())) {
            Date deadline = project.getDeadline();
            deadline.setHours(0);
            Date date = (Date) deadline.clone();
            date.setHours(0);
            date.setMinutes(1);
            wrapper.ge("deadline", date);
            wrapper.le("deadline", deadline);
        }


        IPage<Project> page1 = projectMapper.selectPage(page, wrapper);
        ajaxResult.put("total",page1.getTotal());
        List<Project> projects = page1.getRecords();
        for (Project record : projects) {
            record.setNum(contractMapper.selectCount(new QueryWrapper<Contract>().eq("project_id",record.getId())));
        }
        return projects;
    }

    /**
     * 查询一个项目，浏览量+1
     *
     * @param id
     * @return
     */
    @Override
    public Project queryProjectById(Integer id) {
        Project project = projectMapper.selectById(id);
        if(!Objects.isNull(project)){
            QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("project_id",project.getId());
            List<Task> tasks = taskMapper.selectList(queryWrapper);
            if(!Objects.isNull(tasks))
                Collections.sort(tasks);
            project.setTasks(tasks);
            project.setVisits(project.getVisits()+1);
            List<Contract> contracts = contractMapper.selectList(new QueryWrapper<Contract>().eq("project_id", project.getId()));
            if(contracts.isEmpty()) {
                project.setStudents(Collections.EMPTY_LIST);
            }else {
                List<Integer> stuIds = contracts.stream().map(Contract::getStuId).collect(Collectors.toList());
                List<Student> students = studentMapper.selectList(new QueryWrapper<Student>().in("id", stuIds));
                for (Student student : students) {
                    student.setPassword("");
                }

                project.setStudents(students);
            }
            Teacher teacher = teacherMapper.selectById(project.gettId());
            teacher.setPassword("");
            project.setTeacher(teacher);
            projectMapper.updateById(project);
        }


        return project;
    }

    @Override
    public Map<String, Integer> projectInfo() {
        Map<String,Integer> res = new HashMap<>();
        res.put("recruit",projectMapper.countRecruit());
        res.put("midTerm",projectMapper.countMidTerm());
        res.put("conclusion",projectMapper.countConclusion());
        return res;
    }

    /**
     * 老师查询自己的项目
     *
     * @param index
     * @param size
     * @return
     */
    @Override
    public List<Project> projectsOfTeacher(Integer index, Integer size,AjaxResult ajaxResult) {
        Teacher teacher = SecurityUtils.getTeacher();
        IPage<Project> page = new Page<>(index,size);
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.eq("t_id",teacher.getId()).orderByDesc("release_time");
        IPage<Project> page1 = projectMapper.selectPage(page, wrapper);
        ajaxResult.put("total",page1.getTotal());
        List<Project> records = page1.getRecords();
        for (Project record : records) {
            record.setNum(contractMapper.selectCount(new QueryWrapper<Contract>().eq("project_id",record.getId())));
        }
        return records;

    }

    /**
     * 查询学生的项目
     * @param index
     * @param size
     * @return
     */
    public List<Project> projectsOfStudent(Integer index, Integer size,AjaxResult ajaxResult){
        Student student = SecurityUtils.getStudent();
        IPage<Contract> page = new Page<>(index,size);
        QueryWrapper<Contract> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_id",student.getId()).orderByDesc("sign_time");
        if(size==100000) //查询在职或已完成 的
            wrapper.in("status",Arrays.asList(1,2,0));
        else //查询未离职的
          wrapper.ne("status",3);//不等于3

        IPage<Contract> contractIPage = contractMapper.selectPage(page, wrapper);
        List<Contract> records = contractIPage.getRecords();
        if(records.isEmpty()){
            ajaxResult.put("total",0);
            return Collections.emptyList();
        }
        List<Integer> proIds = records.stream().map(record -> {
          return   record.getProjectId();
        }).collect(Collectors.toList());

        List<Project> projectList = projectMapper.selectBatchIds(proIds);
        for (Project project : projectList) {
            project.setNum(contractMapper.selectCount(new QueryWrapper<Contract>()
                    .eq("project_id",project.getId())
                    .in("status",Arrays.asList(1,2,0))//查询在职或已完成 的
            ));
        }
        Collections.sort(projectList);
        ajaxResult.put("total",contractIPage.getTotal());
        return projectList;
    }

    /**
     * 老师更新一个项目
     *
     * @param project
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateAProject(Project project) {

        projectMapper.updateById(project);
        List<Task> tasks = project.getTasks();
        if(!Objects.isNull(tasks)){
            for (Task task : tasks) {
                int i = taskMapper.updateById(task);
                if(i==0){
                    task.setProjectId(project.getId());
                    taskMapper.insert(task);
                }
            }
        }
        return 1;
    }

    /**
     * 查询某个学院下面的在招聘的项目
     *
     * @param departmentId
     * @param index
     * @param size
     * @return
     */
    @Override
    public List<Project> projectsOfRecruiting(Integer departmentId, AjaxResult ajaxResult, Integer index, Integer size) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        teacherQueryWrapper.eq("dept_id", departmentId);
        List<Teacher> teachers = teacherMapper.selectList(teacherQueryWrapper);
        if(teachers.isEmpty()){ ajaxResult.put("msg","该学院没有项目在招");return Collections.EMPTY_LIST;}
        List<Integer> teacherIds = teachers.stream().map(Teacher::getId).collect(Collectors.toList());

        QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
        projectQueryWrapper.in("t_id",teacherIds);
        projectQueryWrapper.eq("status",0).eq("revoked",0);
        Page<Project> page = projectMapper.selectPage(new Page<>(index, size), projectQueryWrapper);
        List<Project> projectList = page.getRecords();
        ajaxResult.put("total",page.getTotal());
        for (Project project : projectList) {
            int i = resumeMapper.sumRecruited(project.getId());
            project.setNum(i);
        }
        return projectList;
    }

    /**
     * 查询我（学生）投递的项目
     * @return
     */
    @Override
    public List<Project> projectsOfRecruited() {
        Student student = SecurityUtils.getStudent();
      //  if(!Objects.isNull(student)){
            QueryWrapper<ProResume> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stu_id",student.getId());
            List<ProResume> proResumes = resumeMapper.selectList(queryWrapper);
            List<Integer> productsId = proResumes.stream().map(ProResume::getProjectId).collect(Collectors.toList());
            QueryWrapper<Project> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("id",productsId);
           return projectMapper.selectList(queryWrapper1);
        //}
        //return null;
    }

    private boolean updateProject(Project pro){
        int i = projectMapper.updateById(pro);
        return i==1?true:false;
    }
}
